﻿using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Web.Models
{
    //HubName 这个特性是为了让客户端知道如何建立与服务器端对应服务的代理对象，如果没有设定该属性，则以服务器端的服务类名字作为 HubName 的缺省值；
    [HubName("chatHub")]
    public class ChatHub : Hub
    {
        /// <summary>
        /// 加入房间
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="userName"></param>
        public void AddToRoom(string groupId, string userName)
        {
            //将分组Id放到上下文中
            Groups.Add(Context.ConnectionId, groupId);
            //群发人员进入信息提示
            Clients.Group(groupId, new string[0]).addUserIn(groupId, userName);
        }
        /// <summary>
        /// 群组，
        /// </summary>
        /// <param name="groupId"></param>
        /// <param name="detail"></param>
        /// <param name="userName"></param>
        public void Send(string groupId, string detail, string userName)
        {
            //发给某一个组
            Clients.Group(groupId, new string[0]).addSomeMessage(groupId, detail, userName);
        }

        /// <summary>
        /// 通知，所有人都能够看到
        /// </summary>
        /// <param name="detail"></param>
        public void SendAll(string detail)
        {
            Clients.All.allReceiveUser(detail);
        }
        /// <summary>
        /// 发送到指定的用户
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="detail"></param>
        public void SendAppointUser(string userId, string detail)
        {
            string fromUserId = Context.ConnectionId;
            Clients.Client(fromUserId).sendAppoint(fromUserId, userId, detail);
        }




        public static List<UserDetail> ConnectedUsers = new List<UserDetail>();
        /// <summary>
        /// 登录连线，统计在线人数，开启链接
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <param name="userName">用户名</param>
        public void Connect(string userID, string userName)
        {
            var id = Context.ConnectionId;

            if (ConnectedUsers.Count(x => x.ConnectionId == id) == 0)
            {
                if (ConnectedUsers.Count(x => x.UserID == userID) > 0)
                {
                    var items = ConnectedUsers.Where(x => x.UserID == userID).ToList();
                    foreach (var item in items)
                    {
                        Clients.AllExcept(id).onUserDisconnected(item.ConnectionId, item.UserName);
                    }
                    ConnectedUsers.RemoveAll(x => x.UserID == userID);
                }
                //添加在线人员
                ConnectedUsers.Add(new UserDetail { ConnectionId = id, UserID = userID, UserName = userName, LoginTime = DateTime.Now });

                // 反馈信息给登录者
                Clients.Caller.onConnected(id, userName, ConnectedUsers);

                // 通知所有用户，有新用户连接
                Clients.AllExcept(id).onNewUserConnected(id, userID, userName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            }
            else
            {

            }
        }

        /// <summary>
        /// 发送私聊
        /// </summary>
        /// <param name="toUserId">接收方用户连接ID</param>
        /// <param name="message">内容</param>
        public void SendPrivateMessage(string toUserId, string message)
        {
            string fromUserId = Context.ConnectionId;

            var toUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == toUserId);
            var fromUser = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == fromUserId);

            if (toUser != null && fromUser != null)
            {   // send to 
                Clients.Client(toUserId).receivePrivateMessage(fromUserId, fromUser.UserName, message);

                // send to caller user
                //Clients.Caller.sendPrivateMessage(toUserId, fromUser.UserName, message);
            }
            else
            {
                //表示对方不在线
                Clients.Caller.absentSubscriber();
            }
        }

        /// <summary>
        /// 离线
        /// </summary>
        public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
        {
            var item = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);
            if (item != null)
            {
                Clients.All.onUserDisconnected(item.ConnectionId, item.UserName);   //调用客户端用户离线通知
                ConnectedUsers.Remove(item);
            }
            return base.OnDisconnected(stopCalled);
        }

    }
}